<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace App\Http\Controllers\Api\v1\Map;

use App\Tools\Base\Auth;
use App\Tools\Astrolog\Acg;
use App\Exceptions\ApiException;
use App\Models\Api\AppLogicVersion;
use App\Models\Api\FateCity;
use App\Models\Api\Goods;
use App\Models\Api\Map as MapRecode;
use App\Models\Api\Recode;
use App\Models\Api\SystemLogicVersion;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

use Cache;
use DB;

use App\Models\Api\Map as MapModel;


/**
 * @title ACG地图相关接口
 * @desc 查看文章详情<br/>按页码获取文章列表，每页十条<br/>
 * @url /api/v2/article
 * @version 2.0.0
 * Class Article
 * @package app\api\controller\v2
 */
class IndexController extends Auth
{

    protected $MapCollect;

    protected $Map;

    protected $is_active;

    private $gids = [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];

    protected function _initialize()
    {
        parent::_initialize();
        $this->is_active = checktime();
    }

    /**
     * ACG首页 TODO 数据库查询缓存优化
     * @title
     * @method GET
     * @desc
     * @return array
     * @throws ApiException
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(Request $request)
    {
       if (!$request->isMethod('get')) return show(config('code.error'), '未知操作', [], 403);

        $rid = request()->input('rid');

        if (!$rid) return show(config('code.error'), '档案不存在');

        $recode = (new Recode())->getRecode(['id' => $rid]);

        // 获取用户当前已解锁的命格线 string 12位
        $lines = (new MapRecode())->getRecodeUnlockLines(['rid' => $rid, 'uid' => $request->uid, 'isself' => $recode['isself']]);

        $planets = (new Acg())->getPlanetInfo($recode);// 计算客户端绘制命格线所需的数据
        $i = 0;
        foreach ($planets['planet1'] as $k => $d)
        {
            if ($i >= 11) continue;// 仅过滤需要绘制的11颗星的数据中，未解锁购买的

            if ($lines[$i] == 0)
            {
                unset($planets['planet1'][$k]);
                unset($planets['planet2'][$k]);
            }
            $i++;
        }
        $acg_goods = (new Goods())->getGoodsForACG(['id'=>'7']);

        // 从配置文件中加载相关配置
        $icons = config('map.lines_icon');
        $descriptions = config('map.lines_title');
        $colors = config('map.lines_color');
        $pids = config('map.pid');
        $map_planets = config('map.planet');
        $point_titles = config('map.point_title');
        $point_deses = config('map.point_des');

        $line_list = [];// 所有命格线商品

        foreach ($acg_goods as $ag)
        {

            if ($ag['id'] > 18) continue;// 只需要11条线的数据

            $discount = floatval($ag['discount']);// 折扣

            $price = $discount ? $ag['or_prize'] * $discount : $ag['now_prize'];// 计算实际价格

            $is_unlock = $lines[$ag['id'] - 7] == 1;

            $line_list[] = [
                'gid' => $ag['id'],
                'name' => $ag['name'],
                'price' => sprintf("%.2f", $price),
                'icon' => $icons[$ag['id']],
                'description' => $descriptions[$ag['id']],
                'color' => $colors[$ag['id']],
                'is_unlock' => $is_unlock,
                'pid' => $pids[$ag['id']],
                'planet' => $map_planets[$ag['id']],
                'point_title' => $point_titles[$ag['id']],
                'point_des' => $point_deses[$ag['id']],
            ];
        }
        $line_list = resort($line_list, 'is_unlock');// 布尔值进行排序，暂未发现问题????

        $advertising = [
            'is_open' => true,
            'content' => config('map.advertising')['content'],
        ];

        //运营活动
        if ($this->is_active)
        {
            $advertising['content'] = '占星地图89.1元解锁全部,大优惠';
        }

        $fate_city = [];
        // 计算命运之城数据
        if ($lines[11] == 1)
        {
            $info = [
                'uid' => $request->uid,
                'rid' => $rid,// 档案id
                'sex' => $recode['type'],// 档案性别
                'isself' => $recode['isself'],
                'longitude' => ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'],// 用户出生地经度
                'latitude' => ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'],// 用户出生地纬度
                'time' => strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute'])
                    - ($recode['timezone'] + $recode['is_summer']) * 3600,// 用户出生时间
            ];
            $fate_city = (new FateCity())->getUserFateCitys($info);

//            $advertising['is_open'] = false;// 判断商品全部解锁后就关闭喇叭
        }

        if ($advertising['is_open'] === true && ($lines == '111111111111' || !config('map.advertising')['is_open'])) $advertising['is_open'] = false;// 后台控制喇叭关闭

        //更新逻辑数据定义
        $update_logic = [
            'title'=>'',
            'content'=>'',
            'status'=>0
        ];

        //获取当前最新版本逻辑信息
        $SystemLogicModel = new SystemLogicVersion();
        $logic_data  = $SystemLogicModel->getVersion(['type'=>1]);
        //获取当前档案逻辑版本号
        $AppLogicModel = new AppLogicVersion();
        $user_logic = $AppLogicModel->getVersion(['rid'=>$rid,'type'=>1]);
        //新增用户逻辑版本入库
        if (!$user_logic)
        {
            $AppLogicModel->addVersion(['rid'=>$rid,'version'=>1,'type'=>1]);
            $user_logic = Cache::get('logic_1_' . $rid);
        }

        if ($user_logic < $logic_data['version'])
        {
            $update_logic = [
                'title' => $logic_data['title'],
                'content' =>$logic_data['content'],
                'status' => 1,
            ];
        }


        $result = [
            'lines_list' => $line_list,
            'planet1' => $planets['planet1'],
            'planet2' => $planets['planet2'],
            'fate_city' => $fate_city,
            'advertising' => (object)$advertising,
            'help_url' => config('map.help_url'),
            'is_alert' => false, // TODO 弹窗信息未做
            'update_logic' => $update_logic,
        ];

        return show(config('code.success'), '加载成功', $result);
    }


    /**
     * ACG地点详情
     * @return \think\response\Json
     * @throws ApiException
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read()
    {
        if (!request()->isGet()) return show(config('code.error'), '未知操作', [], 403);

        $type = input('get.type');// 地点类型

        $rid = input('get.rid');// 档案id

        if (!$rid) return show(config('code.error'), '档案不存在');

        $current_longitude = input('get.current_longitude');// 所在位置经纬度

        $current_latitude = input('get.current_latitude');// 所在位置经纬度

        $point_longitude = input('get.point_longitude');// 选择点的经纬度

        $point_latitude = input('get.point_latitude');// 选择点的经纬度

        $recode = (new Recode())->getRecode(['id' => $rid]);

        $timestamp = strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute']);

        $timestamp -= ($recode['timezone'] + $recode['is_summer']) * 3600;

        $longitude = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];

        $latitude = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];

        $info = [
            'type' => $type,// 1=>普通地点，2=>命运之地
            'rid' => $rid,// 档案id
            'current_longitude' => $current_longitude,// 当前所在位置经度
            'current_latitude' => $current_latitude,// 当前所在位置纬度
            'point_longitude' => $point_longitude,// 选择的点的经度
            'point_latitude' => $point_latitude,// 选择的点的纬度
            'longitude' => $longitude,// 用户出生地经度
            'latitude' => $latitude,// 用户出生地纬度
            'time' => $timestamp,// 用户出生时间
            'sex' => $recode['type'],// 档案性别
            'isself' => $recode['isself'],// 当前档案是否为自己，检查是否有赠送记录，计算命格线对地点的影响
            'uid' => $request->uid,// 用户id
        ];

        $validate = validate('Map');

        if (!$validate->scene('read')->check($info)) return show(config('code.error'), (string)$validate->getError());
        // 获取选中地点分值
        $array = (new Acg())->getRecommendedInfo($info);
        // 获取选中地点收藏状态
        $collect_status = (new MapModel())->checkCollectStatus(['latitude' => $point_latitude, 'longitude' => $point_longitude, 'uid' => $request->uid, 'rid' => $rid]);

        $array['is_collect'] = $collect_status['is_collect'];
        $array['collect_id'] = $collect_status['collect_id'];

        if ($type == 2) $array['type'] = true;

        return show(config('code.success'), '加载成功', $array);
    }

    /**
     * 命格线列表
     * @throws ApiException
     */
    public function lines_list()
    {
        if (!request()->isGet()) return show(config('code.error'), '未知操作', [], 403);

        $rid = input('get.rid');

        $info = ['rid' => $rid];

        $validate = validate('Map');

        if (!$validate->scene('lines_list')->check($info)) return show(config('code.error'), (string)$validate->getError());

        $where = ['o.uid' => $request->uid, 'og.rid' => $rid, 'o.pay_time' => ['>', 0]];
        // 获取商品信息
        try
        {

            $goods = DB::table('app_goods')
                ->field('id,name,or_prize,now_prize,discount')
                ->where('id', 'in', [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
                ->order('sort', 'DESC')
                ->select();

        } catch (\Exception $e)
        {

            Log::write('商品信息获取失败：' . $e->getMessage(), 'good_info_error', true);

            throw new ApiException('商品获取失败，请稍后再试！', 200, config('code.error'));
        }

        // 获取当前档案购买订单商品信息
        try
        {
            $orders = DB::table('app_orders_goods')
                ->alias('og')
                ->field('og.gid,o.extend,g.name')
                ->join('app_orders o', 'og.oid=o.id', 'LEFT')
                ->join('app_goods g', 'og.gid=g.id', 'LEFT')
                ->where($where)
                ->where('og.gid', 'in', $this->gids)
                ->order('o.pay_time', 'DESC')
                ->select();

        } catch (\Exception $e)
        {

            return show(config('code.error'), $e->getMessage());

        }

        //获取用户是否购买打包
        try
        {
            $pack = DB::table('app_orders_goods')
                ->alias('og')
                ->field('og.gid,o.extend,g.name')
                ->join('app_orders o', 'og.oid=o.id', 'LEFT')
                ->join('app_goods g', 'og.gid=g.id', 'LEFT')
                ->where($where)
                ->where('og.gid', 19)
                ->order('o.pay_time', 'DESC')
                ->findOrFail();
        } catch (\Exception $e)
        {
            $pack = false;
//            return show(config('code.error'), $e->getMessage());
        }

        $map = ['ag.auid' => $request->uid, 'r.isself' => 1];

        //获取当前用户中奖信息
        try
        {

            $aorders = DB::table('wechat.app_award_goods')
                ->alias('ag')
                ->join('wechat.app_goods g', 'ag.agid=g.id', 'LEFT')
                ->join('wechat.app_recode r', 'ag.auid=r.uid', 'LEFT')
                ->field('ag.agid gid,g.name,r.id')
                ->where($map)
                ->where('agid', 'in', $this->gids)
                ->select();

        } catch (\Exception $e)
        {

            return show(config('code.error'), $e->getMessage());

        }

        $aorders_data = [];

        if ($aorders)
        {
            foreach ($aorders as $v)
            {
                $urid = $v['id'];
            }
            if ($urid == $rid)
            {
                $aorders_data = $aorders;
            }
        }

        $ugoods = array_merge($orders, $aorders_data);

        $ugoods = super_unique($ugoods);

        $gid = [];

        foreach ($ugoods as $kk => $vv)
        {
            $gid[] = $vv['gid'];
        }

        $lines = [];

        foreach ($goods as $k => $v)
        {
            $discount = floatval($v['discount']);

            if ($discount)
            {

                $price = strval(number_format($v['or_prize'] * $discount, 2));

            } else
            {

                $price = strval(number_format($v['or_prize'], 2));
            }

            if ($v['id'] == 19)
            {
                $array['pack_price'] = strval(number_format($price, 2));

                //运营活动
                if ($this->is_active)
                {
                    $array['pack_price'] = strval(number_format(89.1, 2));
                }
            }

            $line = [
                'name' => $v['name'],
                'or_price' => $v['or_prize'],
                'now_price' => $price,
                'is_unlock' => false,
                'gid' => $v['id'],
            ];

            if (in_array($v['id'], $gid) || in_array($request->uid, config('map.vip_uid')) || in_array($v['id'], [14, 15]) || $pack) $line['is_unlock'] = true;

            $lines[] = $line;

        }
        // 将解锁的命格线重新排序
        $a = [];
        $b = [];
        foreach ($lines as $k => $v)
        {
            if ($v['is_unlock'])
            {
                $a[] = $v;
            } else
            {
                $b[] = $v;
            }
        }
        $lines = array_merge($a, $b);

        if ($v['gid'] == 19)
        {
            unset($lines[$k]);
        }

        if ($discount)
        {
            $array ['discount_des'] = $discount . '折优惠';
        } else
        {
            $array['discount_des'] = '';
        }

        $array['lines'] = $lines;

        return show(config('code.success'), '加载成功', $array);
    }

}
